/**
 * 设置cookies
 * @param {[String]}
 * @param {[String]}
 */
function setCookie (name, value, days) {
    const Days = days || 7 // 此 cookie 将被保存 30 天
    const exp = new Date() // new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days * 24 * 3600 * 1000)
    document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString() + '; path=/'
}
/**
 * 设置允许子域共享的cookie
 * @param {[String]}
 * @param {[String]}
 */
function setCorsCookie (name, value) {
    // 设置过期时间
    const d = new Date()
    d.setTime(d.getTime() + (7 * 24 * 60 * 60 * 1000))
    const expires = d.toUTCString()
    // 设置共享子域
    const host = location.hostname.split('.')
    const domain = host[1] + '.' + host[2]
    // 设置cookie
    document.cookie = name + '=' + escape(value) + ';domain=' + domain + ';expires=' + expires + ';path=/'
}
/**
 * 清除指定cookie
 * @param  {[String]}
 */
function cleanCookie (name) {
    const exp = new Date()
    exp.setTime(exp.getTime() - 1)
    var cval = getCookie(name)
    if (cval != null) {
        document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() + '; path=/'
    }
}
/**
 * 获取cookie
 * @param  {[String]}
 */
function getCookie (name) {
    const arr = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)(;|$)'))
    if (arr != null) {
        return unescape(arr[2])
    } else {
        return null
    }
}
/**
 * 清除所有cookie
 */
function clearAllCookie () {
    const cookies = document.cookie.split(';')
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i]
        const eqPos = cookie.indexOf('=')
        const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie
        document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/'
    }
    if (cookies.length > 0) {
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i]
            const eqPos = cookie.indexOf('=')
            const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie
            const domain = location.host.substr(location.host.indexOf('.'))
            document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=' + domain
        }
    }
}

// 设置setLocalStorage
function setLocalStorage (key, value) {
    window.localStorage.setItem(key, window.JSON.stringify(value))
}
// 获取getLocalStorage
function getLocalStorage (key) {
    return window.JSON.parse(window.localStorage.getItem(key) || '[]')
}
// 设置setSessionStorage
function setSessionStorage (key, value) {
    window.sessionStorage.setItem(key, window.JSON.stringify(value))
}
// 获取getSessionStorage
function getSessionStorage (key) {
    return window.JSON.parse(window.sessionStorage.getItem(key) || '[]')
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
function treeDataTranslate (data, id, pid) {
    var res = []
    var temp = {}
    for (var i = 0; i < data.length; i++) {
        temp[data[i][id]] = data[i]
    }
    for (var k = 0; k < data.length; k++) {
        if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
            if (!temp[data[k][pid]].children) {
                temp[data[k][pid]].children = []
            }
            if (!temp[data[k][pid]]._level) {
                temp[data[k][pid]]._level = 1
            }
            data[k]._level = temp[data[k][pid]]._level + 1
            temp[data[k][pid]].children.push(data[k])
        } else {
            res.push(data[k])
        }
    }
    return res
}

// 列表设置序号
function setNum (arr, { page, size }) {
    for (let i = 0; i < arr.length; i++) {
        arr[i].num = i + 1 + (page - 1) * size
    }
    return arr
}
// 逗号拼接的字符串转数组
function strToArray (list, str, oldAttr, newAttr) {
    const result = []
    const strArr = str.split(',')
    list.forEach(element => {
        strArr.forEach(item => {
            if (item[oldAttr] === element[oldAttr]) {
                result.push(element[newAttr])
            }
        })
    })
    return result
}
// 遍历区域数组，组成树形
function makeReginTree (list) {
    const arr = []
    list.forEach(element => {
        if (element.level === 1) {
            element.children = []
            arr.push(element)
        }
    })
    arr.forEach(element => {
        element.children = list.filter(e => {
            return e.parentId === element.Id
        })
    })
    arr.forEach(element => {
        element.children.forEach(k => {
            k.children = list.filter(e => {
                return e.parentId === k.Id
            })
        })
    })
    return arr
}
// 遍历菜单数组，组成树形
function makeMenuTree (list) {
    const arr = []
    list.forEach(element => {
        if (element.menuType === 1) {
            element.children = []
            arr.push(element)
        }
    })
    arr.forEach(element => {
        element.children = list.filter(e => {
            return e.menuParentId === element.menuId
        })
    })
    arr.forEach(element => {
        element.children.forEach(k => {
            k.children = list.filter(e => {
                return e.menuParentId === k.menuId
            })
        })
    })
    return arr
}

// 处理返回价格和数字返回的数字
function addComma (str, currentIndex, result) {
    if (currentIndex === undefined) {
        currentIndex = str.length - 1
    }
    if (result === undefined) {
        result = ''
    }
    if (currentIndex < 0) {
        return result
    }
    result = str.charAt(currentIndex) + result
    if ((str.length - currentIndex) % 3 === 0 && currentIndex !== 0) {
        result = ',' + result
    }
    return addComma(str, currentIndex - 1, result)
}

// 判断字符串长度，汉字2个字符英文数字1个
function getByteLen (val) {
    var len = 0
    for (var i = 0; i < val.length; i++) {
        var length = val.charCodeAt(i)
        if (length >= 0 && length <= 128) {
            len += 1
        } else {
            len += 2
        }
    }
    return len
}

// 通用过滤器
function filterCommon (id, list, value, label) {
    for (const element of list) {
        if (element[value || 'value'] === id || element[value || 'value'] === id) {
            return element[label || 'label']
        }
    }
}

// number 处理 .00
function filterFixed (val) {
    if (!val) {
        return Number(0).toFixed(2)
    } else {
        return Number(val).toFixed(2)
    }
}

// 数字转字符串，处理是否带0
function filterNumToStr (val) {
    const num = Number(val)
    return num < 10 ? '0' + num : num.toString()
}

// 通用store值设置
function setState (key, val) {
    this.$store.commit('setState', {
        key,
        val
    })
}

function pointDataFormat (snsType, list, tableMode) {
    // console.log('pointDataFormat snsType:' + snsType)
    var type = {}
    // 过电压保护器是800、820的；过压保护器是串口300的
    if (/温度采集器|过电压保护器|过压保护器/.test(snsType)) {
        type = {
            0: {
                name: '电缆头',
                list: []
            },
            3: {
                name: '上触头',
                list: []
            },
            6: {
                name: '上母排',
                list: []
            },
            9: {
                name: '下触头',
                list: []
            },
            12: {
                name: '下母排',
                list: []
            },
            15: {
                name: '三相一体保护器',
                list: []
            },
            16: {
                name: '保护器A相',
                list: []
            },
            17: {
                name: '保护器B相',
                list: []
            },
            18: {
                name: '保护器C相',
                list: []
            }
        }
        list.forEach(item => {
            if (item.position > -1 && item.position < 3) {
                type[0].list.push(item)
            } else if (item.position > 2 && item.position < 6) {
                type[3].list.push(item)
            } else if (item.position > 5 && item.position < 9) {
                type[6].list.push(item)
            } else if (item.position > 8 && item.position < 12) {
                type[9].list.push(item)
            } else if (item.position > 11 && item.position < 15) {
                type[12].list.push(item)
            } else if (item.position > 14 && item.position < 16) {
                type[15].list.push(item)
            } else if (item.position === 16) {
                type[16].list.push(item)
            } else if (item.position === 17) {
                type[17].list.push(item)
            } else if (item.position === 18) {
                type[18].list.push(item)
            }
        })
        // console.log('utils:type-->' + JSON.stringify(type))
    }
    var row = [
        []
    ]

    if (snsType === '温度采集器') {
        row = [
            [{ text: '' }, { text: 'A相' }, { text: 'B相' }, { text: 'C相' }]
        ]
        for (let key in type) {
            if (type[key].list.length) {
                row.push([{ text: type[key].name }])
                for (let i = 0; i < 3; i++) {
                    let item = type[key].list.find(item => (i + Number(key)) === Number(item.position))
                    // text赋予“ ”，意为未配置；text赋予'--'，意为有配置
                    row[row.length - 1].push(item ? { text: '--', id: item.snsCode, devId: item.id, onlineStatus: item.onlineStatus } : { text: ' ' })
                }
            }
        }
    } else if (snsType === '过压保护器') {
        row = [
            [{ text: '' }, { text: '湿度' }, { text: '温度' }],
            [{ text: '泄露电流' }],
            [{ text: 'A相' }],
            [{ text: 'B相' }],
            [{ text: 'C相' }]
        ]
        for (let key in type) {
            if (type[key].list.length) {
                for (let i = 0; i < 4; i++) {
                    let item = type[key].list.find(item => (i + Number(key)) === Number(item.position))
                    // console.log('item -- > ' + JSON.stringify(item))
                    if (i === 0) {
                        row[i + 1] = [...row[i + 1], item ? { text: item.monitorDataList, id: item.snsCode, devId: item.id, onlineStatus: item.onlineStatus } : { text: '--' }, { text: '' }]
                    } else {
                        row[i + 1] = [...row[i + 1], item ? { text: item.monitorDataList, id: item.snsCode, devId: item.id, onlineStatus: item.onlineStatus } : { text: '--' }, { text: '--' }]
                    }
                    // console.log('row[i + 1] -- > ' + JSON.stringify(row[i + 1]))
                }
            }
        }
        let tmp = row[1]
        row.splice(1, 1)
        row.push(tmp)
    // 过电压保护器是800、820的；过压保护器是300的
    } else if (snsType === '过电压保护器') {
        row = [
            [{ text: '' }, { text: '湿度' }, { text: '温度' }, { text: '动作次数' }],
            [{ text: 'A相' }],
            [{ text: 'B相' }],
            [{ text: 'C相' }],
            [{ text: '泄露电流', length: 2 }],
            [{ text: '电池电压', length: 2 }]
        ]
        // console.log('过电压保护器 row:' + JSON.stringify(list[0]))
        var i = 1;
        ['A', 'B', 'C'].forEach(key => {
            ['humidity', 'temper', 'handoffTimes'].forEach(item => {
                // console.log('item:' + JSON.stringify(item))
                row[i].push({ text: '--', id: list[0].snsCode + item + key, devId: list[0].id })
            })
            i++
        })
        row[4].push({ text: '--', id: list[0].snsCode + 'electric', devId: list[0].id, length: 2 })
        row[5].push({ text: '--', id: list[0].snsCode + 'battery', devId: list[0].id, length: 2 })
    } else if (snsType === '接地管理') {
        row = [
            [{ text: '相位' }, { text: '电压' }, { text: '电流' }],
            [{ text: 'A' }],
            [{ text: 'B' }],
            [{ text: 'C' }],
            [{ text: '0' }]
        ]
        // console.log('接地管理 row:' + JSON.stringify(list[0]))
        for (let i = 1; i < 5; i++) {
            ['voltage', 'electric'].forEach(item => {
                // console.log('item:' + JSON.stringify(item))
                row[i].push({ text: '--', id: list[0].snsCode + item + row[i][0].text, devId: list[0].id })
            })
        }
    } else if (snsType === '电机') {
        list.forEach(item => {
            if (type[item.snsName]) {
                type[item.snsName].push(item)
            } else {
                type[item.snsName] = [item]
            }
        })
        row = [
            [{ text: '安装位置' }],
            [{ text: 'X' }],
            [{ text: 'Y' }],
            [{ text: 'Z' }],
            [{ text: '温度' }],
            [{ text: '电池' }]
        ]
        for (let key in type) {
            if (type[key].length) {
                let text = key
                let item = type[key][0]
                const labelList = ['x', 'y', 'z', 't', 'v']
                if (text.length > 4 && tableMode === 1) {
                    let textList = []
                    let textItem = ''
                    for (let k = 0; k < text.length; k++) {
                        textItem = textItem + text[k]
                        if ((k + 1) % 4 === 0 || k === (text.length - 1)) {
                            textList.push([{ text: '' }, { text: textItem }])
                            textItem = ''
                        }
                    }
                    row[0].push(textList[0][1])
                    row.splice(1, 0, ...textList.slice(1, textList.length))
                    for (let i = 0; i < labelList.length; i++) {
                        row[i + textList.length].push({ text: '--', id: item.snsCode + labelList[i], devId: item.id, onlineStatus: item.onlineStatus })
                    }
                } else {
                    row[0].push({ text })
                    for (let i = 0; i < labelList.length; i++) {
                        row[i + 1].push({ text: '--', id: item.snsCode + labelList[i], devId: item.id, onlineStatus: item.onlineStatus })
                    }
                }
            }
        }
    } else if (snsType === '脉冲采集器') {
        row = [
            [{ text: '编号' }, { text: '柜号' }, { text: '在线' }]
        ]
        list.forEach(item => {
            let onlineText = '离线'
            // console.log('<脉冲采集器>:' + item.snsCode)
            if (item.onlineStatus === 1) {
                onlineText = '在线'
            }
            row.push([{ text: item.snsCode },
                { text: item.snsName },
                { text: onlineText, id: item.snsTypeDetail + item.snsCode, devId: item.id, onlineStatus: item.onlineStatus }])
        })
    } else if (snsType === '快切状态') {
        row = [
            [{ text: '快切状态', length: 4 }],
            [{ text: '相位角', length: 3 }],
            [{ text: '' }, { text: '位置' }, { text: '电压' }, { text: '电流' }],
            [{ text: '工作' }],
            [{ text: '备用' }],
            [{ text: '母线1' }],
            [{ text: '母线2' }]
        ]
        row[1].push({ text: '--', id: list[0].snsCode + 'phaseDeg', devId: list[0].id })
        row[3].push({ text: '--', id: list[0].snsCode + 'workSwitchState', devId: list[0].id })
        row[3].push({ text: '--', id: list[0].snsCode + 'workVoltage', devId: list[0].id })
        row[3].push({ text: '--', id: list[0].snsCode + 'workElec', devId: list[0].id })
        row[4].push({ text: '--', id: list[0].snsCode + 'resSwitchState', devId: list[0].id })
        row[4].push({ text: '--', id: list[0].snsCode + 'resVoltage', devId: list[0].id })
        row[4].push({ text: '--', id: list[0].snsCode + 'resElec', devId: list[0].id })
        row[5].push({ text: '--', id: list[0].snsCode + 'busSwitchState', devId: list[0].id, rowLength: 2 })
        row[5].push({ text: '--', id: list[0].snsCode + 'bus1Voltage', devId: list[0].id })
        row[5].push({ text: '--', id: list[0].snsCode + 'bus1Elec', devId: list[0].id })
        row[6].push({ text: '--', id: list[0].snsCode + 'bus2Voltage', devId: list[0].id })
        row[6].push({ text: '--', id: list[0].snsCode + 'bus2Elec', devId: list[0].id })
    } else if (snsType === '充电柜（900B）') {
        row = [
            [{ text: '充电柜（900B）', length: 2 }],
            [{ text: '进线电流' }, { text: '--', id: list[0].snsCode + 'inElec', position: 'inElec', devId: list[0].id }],
            [{ text: '进线电压' }, { text: '--', id: list[0].snsCode + 'inVoltage', position: 'inVoltage', devId: list[0].id }],
            [{ text: '进线温度' }, { text: '--', id: list[0].snsCode + 'inTemp', position: 'inTemp', devId: list[0].id }],
            [{ text: '地线温度' }, { text: '--', id: list[0].snsCode + 'groundTemp', position: 'groundTemp', devId: list[0].id }],
            [{ text: '环境温度1' }, { text: '--', id: list[0].snsCode + 'envTemp1', position: 'envTemp1', devId: list[0].id }],
            [{ text: '烟雾等级' }, { text: '--', id: list[0].snsCode + 'smokeLvl', position: 'smokeLvl', devId: list[0].id }]
        ]
    } else {
        // console.log('>> item.snsType:' + snsType)
        row = [
            [{ text: snsType, length: 2 }]
        ]
        list.forEach(item => {
            // console.log('item.snsCode:' + item.snsCode)
            row.push([{ text: item.snsName }, { text: '--', id: item.snsCode, devId: item.devId, onlineStatus: item.onlineStatus }])
        })
    }
    if (row && row.length && /温度采集器|过电压保护器|电机/.test(snsType)) {
        row.unshift([{ text: snsType, length: row[0].length }])
    }
    return row
}

function fixNum (num, l = 2) { // num为传入数值,l为小数位数
    // if(String(num).indexOf('.')>-1){
    // 	num = Number(num).toFixed(l)!=0?Number(num).toFixed(l):0.00;
    // };
    num = Number(num).toFixed(l) !== 0 ? Number(num).toFixed(l) : '0.00'
    return num
}

export {
    setNum,
    strToArray,
    makeReginTree,
    makeMenuTree,
    addComma,
    getByteLen,
    filterCommon,
    filterFixed,
    setCookie,
    cleanCookie,
    getCookie,
    clearAllCookie,
    treeDataTranslate,
    setCorsCookie,
    setLocalStorage,
    getLocalStorage,
    setSessionStorage,
    getSessionStorage,
    filterNumToStr,
    pointDataFormat,
    setState,
    fixNum
}
